package com.shigu.item.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.opentae.data.mall.beans.*;
import com.opentae.data.mall.examples.MallAdvertisingExample;
import com.opentae.data.mall.examples.MallHotItemExample;
import com.opentae.data.mall.examples.MallItemExample;
import com.opentae.data.mall.examples.MallItemcatsExample;
import com.opentae.data.mall.interfaces.*;
import com.shigu.MallResponse;
import com.shigu.PageResponse;
import com.shigu.exceptions.AdminException;
import com.shigu.item.bo.AddItemBo;
import com.shigu.item.bo.ModifyItemBo;
import com.shigu.item.vo.ItemIdResponse;
import com.shigu.item.vo.ItemListVo;
import com.shigu.item.vo.ItemsVo;
import com.shigu.item.vo.SelItemResponse;
import com.shigu.postFee.enums.PostFeeType;
import com.shigu.util.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ItemAdminService {
    @Autowired
    MallItemMapper mallItemMapper;
    @Autowired
    MallSkuMapper mallSkuMapper;
    @Autowired
    MallAdvertisingMapper mallAdvertisingMapper;
    @Autowired
    MallPostfeeMapper mallPostfeeMapper;

    @Autowired
    MallHotItemMapper mallHotItemMapper;
    @Autowired
    MallItemcatsMapper mallItemcatsMapper;


    /**
     * 添加商品
     * @description
     * @author 郭尔
     * @date 2019/1/14 12:54
     */
    public MallResponse addItem(AddItemBo bo) throws AdminException {

        if(mallItemMapper.checkSameCode(bo.getItemCode())>0){
            throw new AdminException("该商品编码已存在");
        }
        MallPostfee postfee = mallPostfeeMapper.selectByPrimaryKey(bo.getFeeId());
        if(postfee == null){
            throw new AdminException("不存在该模板");
        }
        if (postfee.getType()== PostFeeType.WEIGHT.getValue()
                && bo.getWeight()==null){
            throw new AdminException("使用计重模板时，请输入商品重量");
        }
        String skuString =  bo.getSkus();
        if(skuString.equals("[]")){
            //如果为空
            skuString = "[{\"name\":\"款式\",\"value\":\"默认\"}]";
        }
        String s = skuString.replaceAll("，",",");
        String[] images = bo.getImages().split(",");

        MallItem item = new MallItem();
        item.setCreateTime(new Date());
        item.setPrice(Double.valueOf(bo.getPrice()));
        item.setDiscount(Double.valueOf(bo.getDiscount()));
        item.setItemCode(bo.getItemCode());
        item.setTitle(bo.getTitle());
        item.setImages(bo.getImages());
        item.setDescription(bo.getDetails());
        item.setOnsale(true);
        item.setFakeSales(bo.getFakeSales());
        item.setSellerId(bo.getSellerId());
        item.setSku(s);
        item.setProductParam(bo.getParams());
        item.setFeeId(bo.getFeeId());
        item.setCid(Long.valueOf(bo.getCid()));
        item.setWeight(bo.getWeight());
        item.setNum(bo.getNum());
        item.setStoreNum(bo.getStoreNum());
        item.setGoodsNo(bo.getGoodsNo());
        if(StringUtils.isNotBlank(bo.getAdvertImg())){
            item.setAdvertImg(bo.getAdvertImg());
        }else {
            //todo 判断主图的数量
            item.setAdvertImg(images[0]+","+images[1]);
        }

        mallItemMapper.insertSelective(item);
        //插入item获取itemid后插入sku数据
        doWithSku(item.getItemId(),exchangeSku(s) );
        return new MallResponse().success();
    }

    /**
     * @description 下架商品
     * @author 郭尔
     * @date 2019/1/14 14:04
     */
    public MallResponse noSaleItem(Long itemId) throws AdminException {
        if (checkAdvert(itemId)) {
            throw new AdminException("该商品已被设置为广告");
        }
        if (checkHotItem(itemId)) {
            throw new AdminException("该商品已被设置为热销");
        }
        MallItem item = new MallItem();
        item.setItemId(itemId);
        item.setOnsale(false);
        mallItemMapper.updateByPrimaryKeySelective(item);
        return new MallResponse().success();
    }

    /**
     * @description 上架
     * @author 郭尔
     * @date 2019/1/14 16:52
     */
    public MallResponse saleItem(Long itemId){
        MallItem item = new MallItem();
        item.setItemId(itemId);
        item.setOnsale(true);
        mallItemMapper.updateByPrimaryKeySelective(item);
        return new MallResponse().success();
    }

    /**
     * @description 修改商品
     * @author 郭尔
     * @date 2019/1/14 14:05
     */
    public MallResponse modifyItem(ModifyItemBo bo) throws AdminException {
        if(mallItemMapper.checkOtherSameCode(bo.getItemCode(),bo.getItemId())>0){
            throw new AdminException("该商品编码已存在");
        }
        String skuString =  bo.getSkus();
        if(skuString.equals("[]")){
            //如果为空
            skuString = "[{\"name\":\"款式\",\"value\":\"默认\"}]";
        }
        String s = skuString.replaceAll("，",",");

        MallItem item = new MallItem();
        item.setItemId(bo.getItemId());

        String old = mallItemMapper.selSkus(bo.getItemId());
        if(!s.equals(old)){
            doWithSku(bo.getItemId(),exchangeSku(s));
        }

        item.setPrice(Double.valueOf(bo.getPrice()));
        item.setDiscount(Double.valueOf(bo.getDiscount()));
        item.setItemCode(bo.getItemCode());
        item.setTitle(bo.getTitle());
        item.setImages(bo.getImages());
        item.setDescription(bo.getDetails());
        item.setOnsale(true);
        item.setFakeSales(bo.getFakeSales());
        item.setSellerId(bo.getSellerId());
        item.setSku(s);
        item.setProductParam(bo.getParams());
        item.setFeeId(bo.getFeeId());
        item.setWeight(bo.getWeight());
        item.setNum(bo.getNum());
        item.setCid(Long.valueOf(bo.getCid()));
        item.setStoreNum(bo.getStoreNum());
        item.setGoodsNo(bo.getGoodsNo());
        mallItemMapper.updateByPrimaryKeySelective(item);

        //修改广告的商品编号
        mallAdvertisingMapper.updateItemCode(bo.getItemId(),bo.getItemCode(),bo.getTitle());

        if(StringUtils.isNotBlank(bo.getAdvertImg())){
            //调用一下修改广告图
            modifyItemAdvert(bo.getItemId(),bo.getAdvertImg());
        }

        return new MallResponse().success();
    }


    /**
     *
     * @description 根据id查商品详情
     * @author 郭尔
     * @date 2019/1/14 14:14
     */
    public SelItemResponse selItemById(Long itemId){
        SelItemResponse response = new SelItemResponse();
        MallItem item = mallItemMapper.selectByPrimaryKey(itemId);
        if(item!=null){
            response.setItemCode(item.getItemCode());
            response.setPrice(item.getPrice());
            response.setDiscount(item.getDiscount());
            response.setTitle(item.getTitle());
            response.setImages(item.getImages());
            response.setDetails(item.getDescription());
            response.setFakeSales(item.getFakeSales());
            response.setSellerId(item.getSellerId());
            response.setSkus(item.getSku());
            response.setParams((item.getProductParam()));
            response.setFeeId(item.getFeeId());
            response.setCid(item.getCid());
            response.setAdvertImg(item.getAdvertImg());
            if(item.getWeight()!=null){
                response.setWeight(item.getWeight());
            }
        }
        return response.success();
    }

    /**
     *
     * @description 商品列表
     * @author 郭尔
     * @date 2019/1/14 16:21
     */
    public PageResponse<ItemListVo> allitemList(int page,int size,Integer status,
                                                String itemCode,String cateId,
                                                String before, String after,
                                                String title,String storeNum,
                                                String goodsNo) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        PageResponse<ItemListVo> response = new PageResponse<>();
        MallItemExample example = new MallItemExample();
        MallItemExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(itemCode)) {
            criteria.andItemCodeEqualTo(itemCode);
        }
        if(status == 2){
            criteria.andOnsaleEqualTo(true);
        }else if(status == 3){
            criteria.andOnsaleEqualTo(false);
        }
        if(StringUtils.isNotBlank(cateId)){
            criteria.andCidEqualTo(Long.valueOf(cateId));
        }
        if(StringUtils.isNotBlank(before)){
            criteria.andCreateTimeGreaterThanOrEqualTo(sdf.parse(before));
        }
        if(StringUtils.isNotBlank(after)){
            criteria.andCreateTimeLessThanOrEqualTo(sdf.parse(after));
        }
        if(StringUtils.isNotBlank(title)){
            criteria.andTitleLike("%"+title+"%");
        }
        if(StringUtils.isNotBlank(storeNum)){
            criteria.andStoreNumLike("%"+storeNum+"%");
        }
        if(StringUtils.isNotBlank(goodsNo)){
            criteria.andGoodsNoEqualTo(goodsNo);
        }

        example.setStartIndex((page-1)*size);
        example.setEndIndex(size);
        example.setOrderByClause("onsale desc,create_time DESC");
        List<MallItem> list = mallItemMapper.selectByConditionList(example);
        int total = mallItemMapper.countByExample(example);
        response.setData(list.stream().map(o->{
            ItemListVo vo = new ItemListVo();
            vo.setDiscount(MoneyUtil.formatPriceMoney(o.getDiscount()));
            //
            if (StringUtils.isNotBlank(o.getAdvertImg())) {
                vo.setAdvertImg(Arrays.asList(o.getAdvertImg().split(",")));
            }
            vo.setItemCode(o.getItemCode());
            vo.setOnsale(o.getOnsale());
            vo.setItemId(o.getItemId());
            vo.setTitle(o.getTitle());
            vo.setCreateTime(sdf.format(o.getCreateTime()));
            //查询商品类目名称
            MallItemcats cate = mallItemcatsMapper.selectByPrimaryKey(o.getCid());
            String manCateName= "";
            if(cate.getParentCid()!=-1){
                MallItemcats mainCate = mallItemcatsMapper.selectByPrimaryKey(cate.getParentCid());

                manCateName = mainCate.getCatName()+"-";
            }

            vo.setCid(o.getCid());
            vo.setCateName(manCateName+cate.getCatName());

            return vo;
        }).collect(Collectors.toList()));
        response.setTotal(total);
        return  response.success();
    }

    /**
     *
     * @description 获取所有排列组合
     * @author 郭尔
     * @date 2019/1/14 12:54
     */
    public List<String> combineAll(List< List<String> > inputList){
        //只有一种sku属性
        if(inputList.size() == 1){
            return inputList.get(0);
        }
        //多余2种
        List<String> arr = inputList.get(0);
        //从1开始,
        for (int i = 1; i <inputList.size(); i++) {
            arr = skuCombine(arr,inputList.get(i));
        }

        return arr;
    }

    private List<String> skuCombine(List<String> list1,List<String> list2){
        List<String> arr = new ArrayList<>();
        for (String a:list1) {
            for (String b:list2) {
                arr.add(a+","+b);
            }
        }
        return arr;
    }

    /**
     * @description  获取sku
     * @author 郭尔
     * @date 2019/1/14 12:57
     */
    public  List<String> exchangeSku(String json){
        JSONArray jsonArray = JSONObject.parseArray(json);
        List< List<String> > list = new ArrayList<>();
        for (int i = 0; i <jsonArray.size() ; i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            String[] values = obj.getString("value").split(",");
            //  System.out.println(JSON.toJSONString(values));
            List<String> strs = new ArrayList<>(Arrays.asList(values));
            list.add(strs);
        }
        return combineAll(list);
    }

    /**
     * @description sku
     * @author 郭尔
     * @date 2019/1/14 12:58
     */
    public void doWithSku(Long itemId,List<String> skus){
        mallSkuMapper.deleteByItemId(itemId);//先删除
        for (String s : skus) {
            MallSku sku = new MallSku();
            sku.setItemId(itemId);
            sku.setSkuValue(s);
            mallSkuMapper.insertSelective(sku);
        }
    }

    /**
     * @description 商品和商品编号
     * @author 郭尔
     * @date 2019/1/18 12:45
     */
    public PageResponse<ItemsVo> items(Integer type){
        PageResponse<ItemsVo> response = new PageResponse<>();
        List<MallItem> list = mallItemMapper.selNotAdvert(type);
        response.setData(list.stream().map(o->{
            ItemsVo vo = new ItemsVo();
            vo.setItemCode(o.getItemCode());
            vo.setItemId(o.getItemId());
            return vo;
        }).collect(Collectors.toList()));

        return  response.success();
    }

    /**
     *
     * @description 删除商品
     * @author 郭尔
     * @date 2019/1/19 14:31
     */
    public MallResponse deleteItem(Long itemId) throws AdminException {

        if (checkAdvert(itemId)) {
            throw new AdminException("该商品已被设置为广告");
        }
        if (checkHotItem(itemId)) {
            throw new AdminException("该商品已被设置为热销");
        }

        mallItemMapper.deleteByPrimaryKey(itemId);
        return new MallResponse().success();
    }

    /**
     *
     * @description 修改商品广告图
     * @author 郭尔
     * @date 2019-06-12 10:55
     */
    public MallResponse modifyItemAdvert(Long itemId,String imgUtrl){
        MallItem item = new MallItem();
        item.setItemId(itemId);
        item.setAdvertImg(imgUtrl);
        mallItemMapper.updateByPrimaryKeySelective(item);


        MallHotItemExample example = new MallHotItemExample();
        example.createCriteria().andItemIdEqualTo(itemId);

        MallHotItem hotItem = new MallHotItem();
        hotItem.setImgUrl(imgUtrl);

        mallHotItemMapper.updateByExampleSelective(hotItem,example);

        return new MallResponse();
    }

    /**
     *
     * @description 商品编号获取id
     * @author 郭尔
     * @date 2019-06-15 12:03
     */
    public ItemIdResponse itemCodeToId(String itemCode) throws AdminException {
        MallItemExample example = new MallItemExample();
        example.createCriteria().andItemCodeEqualTo(itemCode);
        List<MallItem> items = mallItemMapper.selectByExample(example);
        if(items.size()==0){
            throw new AdminException("不存在的商品");
        }
        ItemIdResponse response = new ItemIdResponse();
        response.setItemId(items.get(0).getItemId());
        return response.success();

    }

    private boolean checkAdvert(Long itemId){
        MallAdvertisingExample example = new MallAdvertisingExample();
        example.createCriteria().andItemIdEqualTo(itemId);
        int advertNum = mallAdvertisingMapper.countByExample(example);
        return advertNum >0;
    }

    private boolean checkHotItem(Long itemId){
        MallHotItemExample example = new MallHotItemExample();
        example.createCriteria().andItemIdEqualTo(itemId);
        int num = mallHotItemMapper.countByExample(example);
        return num >0;
    }

}
